<template>
  <el-form ref="form" :model="user" :rules="rules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model.trim="user.username" />
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="user.mobile" maxlength="11" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item label="电子邮箱" prop="email">
      <el-input v-model.trim="user.email" maxlength="50" />
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading" type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { saveProfile } from '@/api/user'

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          username: '',
          mobile: '',
          email: ''
        }
      }
    }
  },
  data() {
    return {
      loading: false,
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          saveProfile({ username: this.user.username, mobile: this.user.mobile, email: this.user.email }).then(res => {
            setTimeout(() => {
              this.$message({
                message: '更新成功',
                type: 'success'
              })
              this.loading = false
            }, 300)
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
